package com.android.fragmentdemo.thread21
import org.junit.Test

class Demo21 {
    @Test
    fun testRunnable() {
        val t1 = Thread {
            for (i in 0.until(5000)) {
                Counter.add()
            }
        }
        t1.start()

        val t2 = Thread {
            for (i in 0.until(5000)) {
                Counter.add()
            }
        }
        t2.start()

        try {
            t1.join()
            t2.join()
        } catch (ex: InterruptedException) {
            ex.printStackTrace()
        }

        println("result:${Counter.count}")

        Thread.sleep(3 * 1000)
    }

    class Counter {
        companion object {
            //静态变量+静态同步方法构成类锁
            var count = 0
            @JvmStatic
            @Synchronized
            fun add() {
                count++
            }
        }
    }
}